package com.anjie.powerproject.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anjie.powerproject.common.FillStrategyEnum;
import com.anjie.powerproject.common.Result;
import com.anjie.powerproject.entity.Model;
import com.anjie.powerproject.pojo.dto.*;
import com.anjie.powerproject.service.EnergyModelService;
import com.anjie.powerproject.service.ModelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 能量模型
 */
@RestController
@RequestMapping(value = "model/energy")
public class EnergyModelController {
    private static final Logger logger = LoggerFactory.getLogger(EnergyModelController.class);

    @Autowired
    EnergyModelService energyModelService;
    @Autowired
    ModelService modelService;

    /**
     * 获得能量模型下拉框填充值
     */
    @RequestMapping(value = "getall")
    public Result<List<ModelVersion>> getall(@RequestParam(value = "deviceCode", required = false) String deviceCode) {
        try {
            return Result.ok(energyModelService.getall(deviceCode));
        } catch (Exception ex) {
            logger.error("查询电量模型列表失败 errmsg={}", ex.getMessage(), ex);
            return Result.error(String.format("查询电量模型列表失败 [%s]", ex.getMessage()));
        }
    }

    /**
     * 使用时间、所选择的模型获取预测能量对比数据
     */
    @RequestMapping(value = "compare")
    public Result<CompareDTO> compare(@RequestBody CompareQueryDTO queryDTO) {
        try {
            return Result.ok(energyModelService.compare(queryDTO));
        } catch (Exception ex) {
            logger.error("获取能量模型比较数据失败 params={} errmsg={}", JSON.toJSONString(queryDTO), ex.getMessage(), ex);
            return Result.error(String.format("获取能量模型比较数据失败 [%s]", ex.getMessage()));
        }
    }

    /**
     * 数据预处理
     */
    @RequestMapping(value = "dataprocess")
    public Result<ProcessDTO> process(HttpServletRequest request, @RequestParam("command") String commandStr, @RequestParam("extraData") MultipartFile[] extraData) {
        try {
            String base = request.getServletContext().getRealPath("WEB-INF/classes/");
            String bases[] = new String[]{base, "src/main/resources/"};
            ProcessCommandDTO commandDTO = JSONObject.parseObject(commandStr, ProcessCommandDTO.class);
            return Result.ok(energyModelService.process(bases, commandDTO, extraData, null, FillStrategyEnum.UNDO));
        } catch (Exception ex) {
            logger.error("预处理失败 params={} errmsg={}", commandStr, ex.getMessage(), ex);
            return Result.error(String.format("预处理失败 [%s]", ex.getMessage()));
        }
    }

    @RequestMapping(value = "dataprocess/{model}")
    public Result<ProcessDTO> process(HttpServletRequest request,
                                      @RequestParam("command") String commandStr,
                                      @RequestParam("extraData") MultipartFile[] extraData,
                                      @PathVariable("model") Integer modelId) {
        try {
            String base = request.getServletContext().getRealPath("WEB-INF/classes/");
            String bases[] = new String[]{base, "src/main/resources/"};
            ProcessCommandDTO commandDTO = JSONObject.parseObject(commandStr, ProcessCommandDTO.class);
            return Result.ok(energyModelService.process(bases, commandDTO, extraData, modelId, FillStrategyEnum.FILL_POSITIVE_ONE));
        } catch (Exception ex) {
            logger.error("预处理失败 params={} errmsg={}", commandStr, ex.getMessage(), ex);
            return Result.error(String.format("预处理失败 [%s]", ex.getMessage()));
        }
    }

    /**
     * 根据历史数据时间段，生成能量模型
     */
    @RequestMapping(value = "create")
    public Result<CreateDTO> create(HttpServletRequest request, @RequestBody ModelCreateCommandDTO commandDTO) {
        try {
            String base1 = request.getServletContext().getRealPath("WEB-INF/classes/");
            String base2 = ResourceUtils.getURL("classpath:").getPath();
            String bases[] = new String[]{base1, base2};
            CreateDTO createDTO=energyModelService.create(bases, commandDTO);
            Integer flag=createDTO.getModelVersion();
            if(flag==-1)
                return Result.error(String.format("模型名重复"));
            else
                return Result.ok(createDTO);
        } catch (Exception ex) {
            logger.error("生成能量模型失败 params={} errmsg={}", JSON.toJSONString(commandDTO), ex.getMessage(), ex);
            return Result.error(String.format("生成能量模型失败 [%s]", ex.getMessage()));
        }
    }

    /**
     * 使用新模型生成一段时间的预测能量
     */
    @RequestMapping(value = "modelpredict")
    public Result<AnalyseDTO> predict(HttpServletRequest request, @RequestBody ModelPredictCommandDTO commandDTO) {
        if(commandDTO.getFlag()==true){ //第一次访问
            Model model=modelService.getModelById(commandDTO.getModelVersion());
            if(model.getStatus()==0){//正在使用(预测)中
                return Result.error(String.format("该模型正在使用(预测)中"));
            }
        }
//        Model model=modelService.getModelById(commandDTO.getModelVersion());
//        if(model.getStatus()==0){//正在使用(预测)中
//            return Result.error(String.format("正在使用(预测)中"));
//        }
        try {
            //预测过程中model.status变成0, 预测完前端发请求给model/modelpredictFeedback，把status变回1
            Model model=modelService.getModelById(commandDTO.getModelVersion());
            model.setStatus(0);
            modelService.save(model);

            String base1 = request.getServletContext().getRealPath("WEB-INF/classes/");
            String base2 = ResourceUtils.getURL("classpath:").getPath() ;
            String bases[] = new String[]{base1, base2};
            return Result.ok(energyModelService.predict(bases, commandDTO));
        } catch (Exception ex) {
            logger.error("使用能量模型预测失败 params={} errmsg={}", JSON.toJSONString(commandDTO), ex.getMessage(), ex);
//            return Result.error(String.format("使用能量模型预测失败 [%s]", ex.getMessage()));
            return Result.error(String.format("能量模型生成出错"));
        }
    }

    /**
     * 设置要选用的能量模型
     */
    @RequestMapping(value = "select")
    public Result<Void> select(@RequestBody ModelSelectCommandDTO commandDTO) {
        try {
            energyModelService.select(commandDTO);
            return Result.ok();
        } catch (Exception ex) {
            logger.error("能量模型设置失败 params={} errmsg={}", JSON.toJSONString(commandDTO), ex.getMessage(), ex);
            return Result.error(String.format("能量模型设置失败 [%s]", ex.getMessage()));
        }
    }
}